package calendar;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author angelika
 */
public class Database {
    File file;
    Map <String, String> events;
    
    public Database() {
        file = new File("database.txt");
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        String stringData = new String();
        try {
            byte[] fileData = Files.readAllBytes(file.toPath());
            stringData = new String(fileData);
        } catch (IOException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        events = new HashMap<>();
        String[] fileEvents = stringData.split("---");
        for (String event : fileEvents) {
            if (event.isEmpty()) {
                continue;
            }
            String[] parts = event.split(": ", 2);
            events.put(parts[0], parts[1]);
        }
    }
    
    public void write(Date date, String event) {
        events.put(date.toString(), event);
        writeToFile();
    }
    
    public String read(Date date) {
        return events.get(date.toString());
    }
    
    private void writeToFile() {
        String stringData = new String();
        for (String date : events.keySet()) {
            stringData += date + ": " + events.get(date) + "---";
        }
        
        byte[] fileData = stringData.getBytes();
        try {
            Files.write(file.toPath(), fileData);
        } catch (IOException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
